<?php
session_start();
// 引入数据库连接代码
include 'conn.php';


// 处理头像上传
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取用户ID
    $user_id = $_SESSION['user_id']; // 假设用户ID存储在 session 中

    // 查询用户之前上传的头像路径
    $getPreviousAvatarSQL = "SELECT image_path FROM users WHERE user_id = $user_id";
    $previousAvatarResult = mysqli_query($conn, $getPreviousAvatarSQL);

    if ($previousAvatarResult && mysqli_num_rows($previousAvatarResult) > 0) {
        $previousAvatarPath = mysqli_fetch_assoc($previousAvatarResult)['image_path'];

        // 删除之前的头像文件
        if (!empty($previousAvatarPath)) {
            unlink($previousAvatarPath);
        }
    }
 
    // 处理头像上传
    if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
        $avatarName = uniqid('avatar_') . '_' . $_FILES['avatar']['name'];
        $avatarPath = './images/touxiang/' . $avatarName;
        move_uploaded_file($_FILES['avatar']['tmp_name'], $avatarPath);

        // 更新数据库中的头像路径
        $updateAvatarSQL = "UPDATE users SET image_path = '$avatarPath' WHERE user_id = $user_id";
        if (mysqli_query($conn, $updateAvatarSQL)) {
            echo '<script>alert("头像上传成功"); window.location.href = "userinfo.php";</script>';
        } else {
            echo "头像更新失败：" . mysqli_error($conn);
        }
    }
}

// 关闭数据库连接
mysqli_close($conn);
?>
